from typing import Any, List, Optional

from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession

from app.api import deps
from app.crud import contact as crud_contact
from app.db.session import get_db
from app.schemas.contacts import Contact, ContactCreate, ContactDetail, ContactUpdate

router = APIRouter()


@router.get("/", response_model=List[Contact])
async def get_contacts(
    db: AsyncSession = Depends(get_db),
    skip: int = 0,
    limit: int = 100,
    keyword: Optional[str] = None,
    relationship_type: Optional[str] = None,
) -> Any:
    """
    获取联系人列表
    
    - **keyword**: 搜索关键词（匹配昵称、备注或微信ID）
    - **relationship_type**: 按关系类型筛选
    - **skip**: 分页偏移量
    - **limit**: 分页条数
    """
    contacts = await crud_contact.search_contacts(
        db, 
        keyword=keyword,
        relationship_type=relationship_type,
        skip=skip, 
        limit=limit
    )
    return contacts


@router.post("/", response_model=Contact)
async def create_contact(
    contact_in: ContactCreate,
    db: AsyncSession = Depends(get_db),
) -> Any:
    """
    创建新联系人
    """
    # 检查联系人是否已存在
    existing_contact = await crud_contact.get_by_wechat_id(db, wechat_id=contact_in.wechat_id)
    if existing_contact:
        raise HTTPException(
            status_code=400,
            detail=f"Contact with wechat_id {contact_in.wechat_id} already exists"
        )
    
    contact = await crud_contact.create(db, obj_in=contact_in)
    return contact


@router.get("/{contact_id}", response_model=ContactDetail)
async def get_contact(
    contact_id: int,
    db: AsyncSession = Depends(get_db),
) -> Any:
    """
    获取联系人详细信息
    """
    contact_with_stats = await crud_contact.get_with_message_stats(db, contact_id=contact_id)
    if not contact_with_stats:
        raise HTTPException(
            status_code=404,
            detail=f"Contact with ID {contact_id} not found"
        )
    
    return contact_with_stats


@router.put("/{contact_id}", response_model=Contact)
async def update_contact(
    contact_id: int,
    contact_in: ContactUpdate,
    db: AsyncSession = Depends(get_db),
) -> Any:
    """
    更新联系人信息
    """
    contact = await crud_contact.get(db, id=contact_id)
    if not contact:
        raise HTTPException(
            status_code=404,
            detail=f"Contact with ID {contact_id} not found"
        )
    
    updated_contact = await crud_contact.update(db, db_obj=contact, obj_in=contact_in)
    return updated_contact